import os,sys
import logging
import json
import time
import pywinio

os.chdir(sys.path[0])

LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='my.log', level=logging.DEBUG, format=LOG_FORMAT)

while True:
    logging.info('start')
    result = {"status": 0, "value": 0, "msg": ""}
    val = sys.stdin.readline().rstrip('\n')
    # logging.info('readed')
    logging.info(val)
    # sys.stdout.write(val)
    # sys.stdout.flush()
    dict_obj = json.loads(val)
    port_address = dict_obj.get('port').get('address')
    port_bit = dict_obj.get('port').get('bit')
    if dict_obj.get("operation") == 'read':       
        readByte=pywinio.WinIO().get_port_byte(port_address)
        readBit = (readByte >> port_bit & 0x01 == 1)
        result['status'] = 1
        result['value'] = readBit
        result['msg'] = ""
        sys.stdout.write(json.dumps(result))
        sys.stdout.flush()
    elif dict_obj.get("operation") == 'write':
        now_val=pywinio.WinIO().get_port_byte(port_address)
        value=dict_obj.get('value')
        if value is True or value==1:
            write_val = now_val | (0x01 << port_bit)
        else:
            write_val = now_val & ~(0x01 << port_bit)
        pywinio.WinIO().set_port_byte(port_address,port_bit)  
        result['status'] = 1
        result['value'] = 1
        result['msg'] = ""  
        sys.stdout.write(json.dumps(result))
        sys.stdout.flush()
    # logging.info(json.dumps(result))
    time.sleep(0.05)